﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MusicAlarm7.Resources;
using MusicAlarm7.DataModel;

namespace MusicAlarm7
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();

            BuildApplicationBar();

            this.DataContext = App.ViewModel;

            //Timer timer = new Timer(new TimerCallback(timer_refresh), null, 60*1000, 60*1000);
        }

        private void timer_refresh(object data)
        {
            this.NotificationListBox.InvalidateArrange();
        }

        private void BuildApplicationBar()
        {
            this.ApplicationBar = new ApplicationBar();
            this.ApplicationBar.IsMenuEnabled = true;
            this.ApplicationBar.IsVisible = true;
            this.ApplicationBar.Opacity = 1.0;
            this.ApplicationBar.Mode = ApplicationBarMode.Default;

            ApplicationBarIconButton addbtn = new ApplicationBarIconButton();
            addbtn.IconUri = new Uri("/Images/appbar.add.rest.png", UriKind.Relative);
            addbtn.Text = AppResources.MainPage_App_AddBtn;
            this.ApplicationBar.Buttons.Add(addbtn);
            addbtn.Click += addbtn_Click;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            ResetItemsList();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            App.ViewModel.Commit();
        }

        private void ResetItemsList()
        {
            this.NotificationListBox.InvalidateArrange();
            this.NotificationListBox.SelectedItem = null;
            App.ViewModel.Commit();
        }

        void addbtn_Click(object sender, EventArgs e)
        {
            App.ViewModel.CurrentAlarm = null;
            NavigationService.Navigate(new Uri("/EditAlarm.xaml", UriKind.RelativeOrAbsolute));
        }

        private void ToggleSwitch_Click(object sender, RoutedEventArgs e)
        {
            ResetItemsList();
        }

        private void NotificationListBox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.ViewModel.CurrentAlarm = (AlarmItem)this.NotificationListBox.SelectedItem;
            NavigationService.Navigate(new Uri("/EditAlarm.xaml", UriKind.RelativeOrAbsolute));
        }
    }
}